<?php

declare(strict_types=1);

namespace App\Traits\Model\Message;


use App\Constants\Message\SmsCode;
use App\Exception\InvalidRequestException;
use function Hyperf\Translation\__;

trait Sms
{
    /**
     * 设置账号
     * @param $value
     */
    public function setAccountAttribute($value):void
    {
        if (checkMobile($value)) {
            $this->attributes['type'] = SmsCode::TYPE_MOBILE;
        } elseif (checkEmail($value)) {
            $this->attributes['type'] = SmsCode::TYPE_EMAIL;
        } else {
            throw new InvalidRequestException(__('validation.account', [
                'attribute' => __('model.field.sms.account')
            ]));
        }
        $this->attributes['account'] = $value;
    }

    /**
     * 设置IP
     * @param $value
     */
    public function setIpAttribute($value):void
    {
        $this->attributes['ip'] = ip2long(getIp());
    }

    /**
     * 设置应用
     * @param $value
     */
    public function setAppAttribute($value)
    {
        $this->attributes['app'] = getApp();
    }

    /**
     * 获取IP
     * @return false|string
     */
    public function getIpTextAttribute():false|string
    {
        return long2ip($this->ip);
    }
}
